<template>
  <div class="promptl">
    <!-- 初始化界面 -->
      <TopFilter
        :list="topFilterList"
        :cols="3"
        :isSubmitBtn='false'
      ></TopFilter>
      <div style="width:100%;">
          <FilterTable
            ref="table"
            :columns="columns"
            :fetchapi="fetchApi"
            :params="fetchParams"
            height="auto"
            :isSelectColumn='false'
            :datakey="'records'"
            :onColumnsChange="columns => this.columns = columns"
          >
            <template slot="controls" slot-scope="props">
              <el-button size="small" type="primary" @click="addhandle">新增职位</el-button>
            </template>
          </FilterTable>
      </div>
      <!-- 弹出框 -->
      <BaseDialog
        :visible.sync="showAddNew"
        :title="title"
        destroyOnClose
        :width="dialogWidth"
        :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto',}">
         <!-- 删除 -->
        <!-- <div v-if="title == '删除'?true:false" style="text-align: center;margin-top: 30px;">
          <p style="padding:0 0 37px 0;">确定删除吗?</p>
            <div slot="footer" class="dialog-footer">
                <el-button @click="closeDialog(false)">取 消</el-button>
                <el-button type="primary" @click="deleteHandler">确 定</el-button>
            </div>
        </div> -->
        <!-- 部门树 -->
        <div class="clearfix"  >
          <div class="leftTree">
            <h3 style="color: #000;font-weight: 900;">选择部门(单选)</h3>
              <div style="position: relative;">
                <span :class="sanjiao"></span>
                <el-tree ref="tree"
                style="margin-top: 12px;"
                v-loading="loading"
                :data="jsonTree"
                node-key="id"
                highlight-current
                :props="defaultProps"
                @node-click="nodeClickHandle"
                @check-change="handleCheckChange"
                :expand-on-click-node="false"
                />
              </div>
          </div>
          <p style="width: 2px;height: 20vw;float: left;background: #f2f2f2;"></p>
          <!-- 角色 -->
          <div class="rightPeople">
            <h3 style="color: #000;font-weight: 900;margin-left: 70px;">选择角色(可多选)</h3>
            <div class="rightPeopleDiv">
              <el-checkbox-group v-model="checkedList" @change="handleCheckedChange"  style="margin-left: 20px;width: 18%;margin: 20px;">
                <el-checkbox style="margin:5px 0;width:100%;" v-for="role in sites" :label="role.roleId" :key="role.roleId+'C'" :value="role.roleId">{{role.roleName}}</el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
          <el-button class="rightPeopleBtn" style="position: absolute;right: 25px;bottom: 10px;" size="small" type="primary" icon="el-icon-plus" :loading="saveLoading"  @click="confirm">确定</el-button>
        </div>

      </BaseDialog>
      <!-- 权限管理 -->
      <Drawer
        :visible.sync="visible"
        title="权限管理"
        :width="920"
        destroyOnClose
        :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
      >
        <EmployeeAuthPanel @close="closeHandler" :emIsShow='emIsShow' :UserData="UserData" @handleShow="handleShow" :rowData='rowData' :treeDataName="treeDataName" :type1='type1'/>
      </Drawer>
  </div>
</template>

<script>
  import { mapState } from 'vuex';
  import { searchRoleEmp,lockflag,removeLockflag,getRole,getEmployeeNo,confirmRole,deleteUserOrgId} from '@/api/common/auth/employeeAuth'
  import { dictionary } from '@/utils/dictMixin';
  import { getJsonTree,codeCheck } from '@/utils/index';
  import {getChildOrgTreeList} from '@/api/common/org/companyOrgManage'
  import EmployeeAuthPanel from './employeeAuthPanel.vue'
  export default {
    name: 'promptl',
    mixins: [dictionary],
    props:['employeeNo','promptlType','employeeName','jurisdictionData'],
    data() {
      this.BaseTable = null;
      return {
        dialogWidth:'70%',
        title:'',
        topFilterList: this.createTopFilterList(),
        visible: false,
        fetchApi: getEmployeeNo,
        fetchParams: { xhrAbort: false,employeeNo:this.employeeNo},
        columns: this.createTableColumns(),
        showAddNew: false,
        roleId: '',
        rowData:null,
        type1:'edit',
        isShow:true,
        emIsShow:"",
        checkedList:[],
        treeData:[],
        treeDataName:'',
        sites:[],
        loading:false,
        jsonTree:[],
        defaultProps: {
          children: 'children',
          label: 'text'
        },
        tree: [],
        params:{
            orgId:0,
            type:10011001,
        },
        RoleEmployeeNo:'',
        UserData:'',
        isAdd:1,
        sanjiao:'sanjiao',
        potUserOrgId:"",
        saveLoading: false
      };
    },
    components: {
      EmployeeAuthPanel,
    },
    methods: {
       init(){
        //  getEmployeeNo(this.fetchParams).then(res=>{
        //   // console.log(res,"getEmployeeNo")
        //   this.RoleEmployeeNo = res.data.records[0].employeeNo
        // })
        console.log(this.jurisdictionData,"jurisdictionData",this.promptlType)
        if(this.jurisdictionData){
          this.topFilterList[1].initialValue=this.jurisdictionData.employeeName
          this.topFilterList[0].initialValue=this.jurisdictionData.employeeNo
          this.RoleEmployeeNo = this.jurisdictionData.employeeNo;
        }else if(this.promptlType == "deploy"){
          this.topFilterList[1].initialValue=this.employeeName
          this.topFilterList[0].initialValue=this.employeeNo
          this.RoleEmployeeNo = this.employeeNo;
        }

      },
      getCookie(){
        let allCookie=document.cookie.split(';')
        allCookie.forEach(x=>{
          if(x.indexOf('dataType') > -1 ){
            this.dataType=x.split('=')[1]
            }
        })
        //判断是否为车厂10461003
        console.log(this.dataType,"dataType")
        if(this.dataType == 10461003){
          console.log(this.dataType,"车厂")
          this.emIsShow=true
        }else{
          this.emIsShow=false
        }
      },
      getCheckedList(orgId,isAdd){
        // getRole
          this.sites=[]
          getRole(this.RoleEmployeeNo,orgId,isAdd)
            .then(res => {
              this.sites = _.cloneDeep(res.data)
            })
            .catch(err => {
            })
      },
      createTableColumns() {
        return [
          {
            title: '操作',
            dataIndex: 'column-action',
            width: 140,
            fixed: 'left',
            render: props => {
              return (
                <div>
                  <el-button size="mini" type="text" onClick={()=>this.detail(props.row,"编辑")}>
                    编辑
                  </el-button>
                  <el-divider direction="vertical" />
                  <el-button size="mini" type="text" onClick={()=>this.detail(props.row,"删除")}>
                    删除
                  </el-button>
                </div>
              );
            }
          },
          {
            title: '序号',
            dataIndex: 'index',
            width: 70,
            sorter: true,
            render: props => {
              return <span>{props.row.index + 1}</span>;
            }
          },
          {
            title: '部门角色',
            dataIndex: 'position',
            sorter: true,
            filter: true,
            filterType: 'input',
            // align:"center"
          }
        ];
      },
      createTopFilterList() {
        return [
          {
            type: 'INPUT',
            label: '员工编号',
            fieldName: 'employeeNo',
            placeholder: '员工编号...',
            style: { width: '200px' },
            readonly:"true"
          },
          {
            type: 'INPUT',
            label: '员工姓名',
            fieldName: 'employeeName',
            placeholder: '员工姓名...',
            style: { width: '200px' },
            readonly:"true"
          },
        ];
      },
      // 权限配置
      jurisdiction(row){
        // console.log(row,"jurisdiction")
      },
      // 重置密码
      resetPassword(row) {
        //  console.log(row,"resetPassword")
      },
      //加载树
    async searchTree() {
      this.loading = true;
      // let param = `${this.rowData.employeeId}/${this.rowData.dataSources}`;
      const res = await getChildOrgTreeList(this.params);
      this.jsonTree.push(res.data[0])
      // this.tree = res.data.treejson;
      this.loading = false;
      //this.getJsonTreeData()
    },
      // 加载树
      // getJsonTreeData() {
      //   this.tree.forEach(el => (el.label = el.text));
      //   this.tree.forEach(el => (el.parentId = el.parent));
      //   this.jsonTree=getJsonTree(this.tree)
      //   this.jsonTree=_.unionBy(this.jsonTree, 'id')
      //   // return getJsonTree(this.tree);
      // },
      //树点击
      nodeClickHandle(data) {
        this.sanjiao=""
        // console.log(data,"树点击")
        if(data != "" || data != "undefined"){
            this.params.orgId=data.orgId
            getChildOrgTreeList(this.params).then((res)=>{
                data.children=res.data
            }).catch(err=>{})
        }
        // console.log(this.type1,"this.type1")
        if(!this.type1){
          this.isAdd = 1
        }else{
          this.isAdd = 0
        }
        this.getCheckedList(data.orgId,this.isAdd)
        this.treeData=data.orgId
        this.treeDataName=data.text
      },
      //树选择
      handleCheckChange(val){
        // this.treeData=_.uniq(this.treeData)
      },
      //新增
      addhandle(){
          this.title='新增职位'
          this.showAddNew =true
          this.dialogWidth="70%"
          this.type1='addPot'
          this.checkedList=[]
      },
      //多选角色
      handleCheckedChange(val){
        this.checkedList=_.uniq(val)
      },
      //抽屉组件控制显示
      handleShow(data,type,orgId,rowData){
        this.showAddNew =data
        console.log(orgId,"pointName",rowData)
        if(type == 'edit'){
          this.potUserOrgId=rowData.userOrgId
          this.checkedList=[]
          this.sites=[]
        }else{
          this.potUserOrgId=orgId
        }
      },
      // 确定
      confirm(){
        console.log(this.checkedList,this.treeData,"confirm")
        let params={
          employeeNo:this.employeeNo,
          orgId:this.treeData,
          roleId:this.checkedList,
          userOrgId:this.potUserOrgId?this.potUserOrgId:""
        }
        this.saveLoading = true;
        confirmRole(params).then(res=>{
          if(res.resultCode == 200){
              this.saveLoading = false;
            this.UserData=res.data
            this.visible = true;
            // this.rowData = params;
            this.closeDialog()
          }else{
              this.saveLoading = false;
            this.rowData = params;
            this.closeDialog()
          }

        })

      },
      //删除
      deleteHandler(){
        this.showAddNew =false
      },
      // 关闭
      closeDialog(val,type) {
        this.showAddNew = val
        if (type === 'refresh') {
          // 重新加载
          this.fetchParams = { ...this.fetchParams };
        }

        if(type == 'deploy'){
          this.isShow = val
        }
      },
      // 返回
      backHandle(){
        this.isShow =true
      },
      closeHandler(val,type) {
        this.visible = val;
        if (type === 'refresh') {
          // 重新加载
          this.fetchParams = { ...this.fetchParams };
        }
      },
      detail(data,dataTypes) {
        // console.log(data,"data.")
        if(dataTypes == '删除'){
          this.title='删除'
          this.open(data.userOrgId)
        }else{
          this.visible = true;
          this.type1='edit'
          this.rowData = data;
        }
        //
        this.treeDataName=this.rowData.position
      },
      //确定删除
        open(userOrgId){
          this.$confirm('确定删除?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            deleteUserOrgId(userOrgId).then(res=>{
              if(res.resultCode == 200){
                    this.$message({
                    type: 'success',
                    message: '删除成功!'
                  });
                  // 重新加载
                   this.fetchParams = { ...this.fetchParams };
              }
            })

          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          });
        },



    },

    mounted() {
      this.BaseTable = this.$refs.table.$refs.pageTable;
      this.init()
      this.getCookie()
      // 加载树
      this.searchTree()
    }
  };
</script>

<style lang="less" >
  .clearfix::after {
    content: '';
    height: 0;
    visibility: hidden;
    clear: both;
    display: block;
  }
  .clearfix {
    zoom: 1;
  }
  .el-checkbox+.el-checkbox {
      margin-left: 0px;
    }

    .el-checkbox {
      margin-right: 25px;
    }

    .menu-header {
      height: 30px;
      line-height: 30px;
      margin-bottom: 5px;
      background: #eee;
      text-indent: 5px;
    }
    .leftTree{
      float: left;
      width:40%;
    }
    .rightPeople{
      float: left;
      width: 56%;
      .rightPeopleDiv{
        width: 100%;
        min-height: 20vw;
        padding-left: 50px;
        background: #f2f2f2;
      }
    }
    .sanjiao{
          position: absolute;
          left: 10px;
          top: 8px;
          z-index: 99;
          width: 0;
          height: 0;
          border-top: 3px solid transparent;
          border-bottom: 5px solid transparent;
          border-left: 9px solid #ccc;
    }
</style>
